package com.wjw.utils.sms;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.wjw.utils.HttpUtil;

/**
 * @desc 短信发送工具类
 * http://ihuyi.cn/ 互亿无线短信接口
 * @author wjw 
 * @date 2016年11月24日下午5:38:54
 */
public final class SmsClientHywx {

    /**
     * 日志对象
     */
    protected static Logger log = LoggerFactory.getLogger(SmsClientHywx.class);
    
//	短信回执xml格式
//	String text = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" 
//			+ "<SubmitResult xmlns=\"http://106.ihuyi.cn/\">"
//				+ "<code>2</code>" 
//				+ "<msg>提交成功</msg>" 
//				+ "<smsid>298313649</smsid>" 
//			+ "</SubmitResult>";
    private static final Pattern RESULT_PATTERN = Pattern.compile("<submitresult xmlns=\"http://106.ihuyi.cn/\">(.*?)</submitresult>",Pattern.MULTILINE);
	
	private String url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";//短信发送服务器地址
	private String account;//账户
	private String password;//密码

	public SmsClientHywx() {
	}
	
	/** 构造器 */
	public SmsClientHywx(String url,String account,String password) {
		this.url=url;
		this.account=account;
		this.password=password;
	}
	
	/**  发送短信 */
	public void send(final Sms sms) {
		Thread t=new Thread(new Runnable() {
			@Override
			public void run() {
				try{
					Map<String, String> queryParas = new HashMap<String, String>();
					queryParas.put("account", account);
					queryParas.put("password",password);
					queryParas.put("mobile", sms.getMobile());
					queryParas.put("content",sms.getContent());//格式化短信内容
					log.info("短信实体信息："+JSONObject.toJSONString(queryParas));
					String responseText = HttpUtil.get(url, queryParas);
					// 对结果进行解析
		            RestResult result = parseResult(responseText);
		            String code = result.getCode();
					log.info("短信发送状态：\tmobile:"+sms.getMobile()+"\t code:"+sms.getMobile()+"\t发送是否成功:" + ( code.equals("2")?"true":"false" ));
					if (code.equals("2")) {
						log.info("短信发送成功！");
					} else if (code.equals("4085")) {
						log.error("发送失败，已经超过五次");
					} else {
						log.error("发送失败！");
					}
				}catch(Exception e){
					e.printStackTrace();
					log.error("网络异常！");
				}
			}
		});
		t.start();
	}
	
    /** 解析result */
    private RestResult parseResult(String content) {
    	content = content.toLowerCase();//全部转换小写
        RestResult result = null;
        Matcher matcher = RESULT_PATTERN.matcher(content);
        if (matcher.find()) {
            result = new RestResult();
            String data = matcher.group(1);
            result.setCode(getParameter(data, "code"));
            result.setMsg(getParameter(data, "msg"));
            result.setSmsid(getParameter(data, "smsid"));
        }
        return result;
    }
	
	/** 解析正则表达式 */
	public static String getParameter(String data, String para) {
		String result = "";
		StringBuffer reStr = new StringBuffer();
		reStr.append("<");
		reStr.append(para);
		reStr.append(">");
		reStr.append("(.*?)");
		reStr.append("</");
		reStr.append(para);
		reStr.append(">");
		Pattern pattern = Pattern.compile(reStr.toString());
		Matcher matcher = pattern.matcher(data);
		if (matcher.find()) {
			result = matcher.group(1);
		}
		return result;
	}
	
	/**
     * 内部类短信结果实例
     */
    private static class RestResult {
        
        /** 错误码  */
        private String code;
        /** 消息  */
        private String msg;
        /** 第三方短信消息id */
        private String smsid;
        
		public String getCode() {
			return code;
		}
		public void setCode(String code) {
			this.code = code;
		}
		public String getMsg() {
			return msg;
		}
		public void setMsg(String msg) {
			this.msg = msg;
		}
		public String getSmsid() {
			return smsid;
		}
		public void setSmsid(String smsid) {
			this.smsid = smsid;
		}
    }
}